package com.greensecurity.sim.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.greensecurity.sim.entity.Green;
import com.greensecurity.sim.entity.GreenLand;
import com.greensecurity.sim.entity.GreenLandPhoto;
import com.greensecurity.sim.entity.User;
import com.greensecurity.sim.service.UserService;
import com.greensecurity.sim.service.impl.UserServiceImpl;
import com.greensecurity.sim.util.IsWindowOrLinuxUtils;
import com.greensecurity.sim.util.SplitUser;
import com.greensecurity.sim.util.batdownload.Base64Util;
import com.greensecurity.sim.util.batdownload.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;


@Controller
@RequestMapping("/user")
@Slf4j
@Api(description = "用户管理接口")
public class UserController {


    @Autowired
    UserService userService;

    @ApiOperation(value = "获取全部用户信息")
    @ResponseBody
    @RequiresPermissions("query")
    @GetMapping("/findAll")
    public List<User> findAll() {
        List<User> user = userService.findAll();
        for (User userOne :user){
            userOne.setUserPhotoUrl(IsWindowOrLinuxUtils.getPhotoUrl()+userOne.getUserPhotoUrl());
//        给绿地图片赋值
            List<GreenLand>  greenLandList = userOne.getGreenLands();
            for (GreenLand greenLand: greenLandList){
                for (GreenLandPhoto greenLandPhoto : greenLand.getGreenLandPhotos()){
                    greenLandPhoto.setPhotoUrl(IsWindowOrLinuxUtils.getPhotoUrl()+greenLandPhoto.getPhotoUrl());
                }
            }
        }
        return user;
    }

    @ApiOperation(value = "通过ID获取用户信息")
    @RequiresPermissions("query")
    @GetMapping("/findUserById/{id}")
    public Optional<User> findUserById(@PathVariable Long id) {
        Optional<User> user = userService.findById(id);
        return user;
    }

    @PostMapping("/updateUser")
    @ResponseBody
    public String updateUser(@RequestBody User user){
        Long userId =Long.valueOf(user.getId());
        User userSave = userService.findById(userId).get();
        user.setUserPhotoUrl(userSave.getUserPhotoUrl());
        user.setGreenLands(userSave.getGreenLands());
        userService.save(user);
        return "保存成功";
    }

    @PostMapping("/delUser")
    @ResponseBody
    public String delUser(@RequestBody User user){
        userService.del(user);
        return "删除成功";
    }

    @ApiOperation(value = "通过ID获取用户信息")
    @RequiresPermissions("query")
    @ResponseBody
    @GetMapping("/findUserByPhone/{phone}")
    public User findUserByPhone(@PathVariable String phone) {
        User user = userService.findByPhone(phone);
        user.setUserPhotoUrl(IsWindowOrLinuxUtils.getPhotoUrl()+user.getUserPhotoUrl());
//        给绿地图片赋值
        List<GreenLand>  greenLandList = user.getGreenLands();
        for (GreenLand greenLand: greenLandList){
            for (GreenLandPhoto greenLandPhoto : greenLand.getGreenLandPhotos()){
                greenLandPhoto.setPhotoUrl(IsWindowOrLinuxUtils.getPhotoUrl()+greenLandPhoto.getPhotoUrl());
            }
        }
        List<Green>  greens = user.getGreen();
        for (Green green: greens){
            for (GreenLandPhoto greenLandPhoto : green.getGreenLandPhotos()){
                greenLandPhoto.setPhotoUrl(IsWindowOrLinuxUtils.getPhotoUrl()+greenLandPhoto.getPhotoUrl());
            }
        }
        return user;
    }
    @ApiOperation(value = "通过数据库用户头像的Url去生成Base64编码返回前端显示")
    @RequiresPermissions("query")
    @ResponseBody
    @GetMapping("/getBase64ThroughUserPhotoUrl")
    public String getBase64ThroughUserPhotoUrl(String userPhotoUrl) {
//        JSONObject jsonObject = JSON.parseObject(String.valueOf(user))
        byte[] imgData;
        String imgStr;
        try {
            imgData = FileUtil.readFileByBytes(userPhotoUrl);
            imgStr = Base64Util.encode(imgData);
        } catch (IOException e) {
            throw new RuntimeException("图片路径错误，请重新上传");
        }
        return "data:image/jpeg;base64,"+imgStr;
    }
    @ApiOperation(value = "增加用户")
    @ResponseBody
    @PostMapping("/addUser")
    public String addUser(@RequestBody User user){
        try {
            User isRegister = userService.findByPhone(user.getPhone());
            try {
                if (isRegister.getPhone() != null){
                    throw new RuntimeException("新增用户失败:手机号已存在");
                }
            }catch (Exception e){}
//            密码加密
            String passwordMd5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(passwordMd5);
            user.setUserId(Long.valueOf(1));
            user.setCreateTime(new Date());
            userService.save(user);
            return "新增用户成功";
        }catch (Exception e){
            log.error(String.valueOf(e));
            throw new RuntimeException("新增用户失败:"+e.getMessage());
        }
    }


    @ApiOperation(value = "查询所有用户数量：失败")
    @ResponseBody
    @GetMapping("/selectAllUser")
    public String selectAllUser(){
        try {
            Integer userNum = userService.selectAllUserNum();
            return String.valueOf(userNum);
        }catch (Exception e){
            log.error(String.valueOf(e));
            throw new RuntimeException("查询用户失败");
        }
    }

    @ApiOperation(value = "查询角色所有用户数量:失败")
    @ResponseBody
    @GetMapping("/selectRoleUser/{roleId}")
    public String selectAllUser(@PathVariable String roleId){
        try {
            String userNum = userService.selectRoleUserNum(roleId);
            return userNum;
        }catch (Exception e){
            log.error(String.valueOf(e));
            throw new RuntimeException("查询角色用户失败");
        }
    }


    @ApiOperation(value = "重置用户密码")
    @RequiresPermissions("query")
    @ResponseBody
    @GetMapping("/resetPwd/{phone}")
    public String resetPwd(@PathVariable String phone) {
        User user=userService.findByPhone(phone);
        String pwd = DigestUtils.md5DigestAsHex("123456".getBytes());
        user.setPassword(pwd);
        userService.save(user);
        return pwd;
    }

    @ApiOperation(value = "修改密码")
    @RequiresPermissions("query")
    @ResponseBody
    @PostMapping("/changePwd")
    public String changePwd(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        String oldPwd =DigestUtils.md5DigestAsHex(jsonObject.get("oldPwd").toString().getBytes());
        Long userId = Long.valueOf(jsonObject.get("userId").toString());
        User user = userService.findById(userId).get();
        String newPwd;
        if (user.getPassword().equals(oldPwd)){
            newPwd =DigestUtils.md5DigestAsHex(jsonObject.get("newPwd").toString().getBytes());
            user.setPassword(newPwd);
            userService.save(user);
        }else {
            throw new RuntimeException("原密码不正确");
        }
        return newPwd;
    }

}
